package showtime.framework.core.pattern
{
	import flash.errors.IllegalOperationError;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;

	/**
	 * Unit singleton instane manager. 
	 * @author yinhao
	 * 
	 */	
	public class Singleton extends EventDispatcher
	{
		private static var singletonDict:Dictionary = new Dictionary();
		
		/**
		 * Constructor. 
		 * 
		 */		
		public function Singleton(target:IEventDispatcher = null)
		{
			super(target);
			
			var key:Class = this["constructor"] as Class;
	
			if (singletonDict[key])
			{
				throw new IllegalOperationError(getQualifiedClassName(this) + " only one instance!");
			}
			else
			{
				singletonDict[key] = this;
			}
			
			initialize();
		}
		
		/**
		 * Initialize some useful variables. 
		 * 
		 */		
		protected function initialize():void
		{
			
		}
		/**
		 * 
		 * Destroy all singleton instance. 
		 * 
		 */		
		protected function dispose():void
		{
			var key:Class = this["constructor"] as Class;
			
			delete singletonDict[key];
		}
		
		/**
		 * 
		 * Get singleton instance, return null if not exist. 
		 * @param key
		 * @return 
		 * 
		 */		
		public static function getInstance(key:Class):*
		{
			return singletonDict[key];		
		}
		
		/**
		 * 
		 * Get singleton instance,Or create if not exist. 
		 * @param key
		 * @return 
		 * 
		 */		
		public static function getInstanceOrCreate(key:Class):*
		{
			if (singletonDict[key] == null)
			{
				singletonDict[key] = new key();
			}
			
			
			return singletonDict[key];
		}
		
	}
}